import { PageContainer } from '@ant-design/pro-components';
import React, { useEffect, useState } from 'react';
import { Card, List, Avatar, Modal, Button, Input, Space, Table, message, Pagination, Flex } from 'antd';
import useUser from "@/models/user";
import { api } from "@/utils/api";
import type { ModalProps } from 'antd';
import './index.less';
import styles from "@/pages/Home/index.less";
import Guide from "@/components/Guide";

const { TextArea } = Input;

interface ICreativeTask {
  id: number;
  state_name: string;
  prompt: string;
  size: string;
  credit: number;
}

interface ICreativeItem {
  id: string;
  task: ICreativeTask;
  thumb_path: string;
  image_path: string;
  is_public: boolean;
  created_at: string;
}

const UserCenter: React.FC = () => {
  const [ messageApi, contextHolder ] = message.useMessage();
  const [ loginDisableState, setLoginDisableState ] = useState(false)

  const [ creativeTaskList, setCreativeTaskList ] = useState<ICreativeTask[]>([]);
  const [ creativeTaskListParam, setCreativeTaskListParam ] = useState({page: 1, total: 0})

  const { user, setUser } = useUser()
  const [ creativePage, setCreativePage ] = useState(1);
  const [ creativeTotal, setCreativeTotal ] = useState(0);
  const [ pageLoading, setPageLoading ] = useState(false);
  const [ creatives, setCreatives ] = useState<ICreativeItem[]>([]);

  const [ selectedCreative, setSelectedCreative ] = useState<ICreativeItem | null>(null);
  const [ isModalVisible, setIsModalVisible ] = useState(false);
  useEffect(() => {
    if (!isModalVisible) {
      setSelectedCreative(null)
    }
  }, [isModalVisible]);

  const handleViewCreative = (item: ICreativeItem) => {
    setSelectedCreative(item);
    setIsModalVisible(true);
  };

  const handleModalClose: ModalProps['onCancel'] = () => {
    setIsModalVisible(false);
  };

  async function loadCreatives() {
    try {
      const creatives = await api(`creative/list?token=${ user?.login_token }&page=${ creativePage }`);
      setCreatives(creatives.data);
      setCreativeTotal(creatives.total);
    } catch (e: Error | any) {
      console.error(e);
      messageApi.open({
        type: 'error',
        content: <div>获取创意列表失败: { e?.message }</div>,
      });
    } finally {

    }
  }

  useEffect(() => {
    if (!user) {
      return;
    }

    (async function () {
      await loadCreatives();
    })()
  }, [ user, creativePage ]);

  async function doLogin(orderNo: string) {
    setLoginDisableState(true);
    setPageLoading(true);
    try {
      const user = await api(`user/user?token=${ orderNo }`);
      localStorage.setItem('login-token', orderNo);
      setUser(user);
    } catch (e: Error | any) {
      messageApi.open({
        type: 'error',
        content: <div>登录失败: { e?.message }</div>,
      });
      console.error(e);
    } finally {
      setLoginDisableState(false)
      setPageLoading(false);
    }
  }

  useEffect(() => {
    const token = localStorage.getItem('login-token');
    if (!token) {
      return;
    }
    doLogin(token);
  }, []);

  useEffect(() => {
    if (!user) {
      setCreativeTaskList([]);
      return;
    }
    (async function () {
      let tasks = await api(`creative-task/list?token=${user.login_token}`)
      setCreativeTaskList(tasks.data);
      setCreativeTaskListParam({page: tasks.current_page, total: tasks.total})
    })()
  }, [ creativeTaskListParam.page, user?.login_token ]);

  const [ createModal, setCreateModal ] = useState(false);
  const [ createTaskModel, setCreateTaskModel ] = useState(false)
  const [ confirmLoading, setConfirmLoading ] = useState(false);
  const [ prompt, setPrompt ] = useState("");
  const handleOk = () => {
    setConfirmLoading(true);
    (async function () {
      try {
        await api('creative-task/create', {
          "token": user?.login_token,
          "prompt": prompt,
        });
        messageApi.open({
          type: 'success',
          content: '创意提交成功，请等待生成',
        });
      } catch (e: Error | any) {
        console.log(e)
        messageApi.open({
          type: 'error',
          content: <div>{ e?.message }</div>,
        });
      } finally {
        setCreateModal(false);
        setConfirmLoading(false);
      }
    })()
  };

  const handleCancel = () => {
    setCreateModal(false);
  };

  const [ orderNo, setOrderNo ] = useState("")
  if (!user) {
    return <PageContainer ghost>
      { contextHolder }
      <div className={ styles.container }>
        <Guide name={
          <>
            <div style={ { textAlign: 'center' } }>请输入一个爱发电的订单号开启创意体验</div>
            <hr/>
            <Space.Compact
              style={ {
                width: 480,
                textAlign: 'center',
              } }
            >
              <Input placeholder="请输入订单号" value={ orderNo } onChange={ (e) => setOrderNo(e.target.value) }/>
              <Button type="primary" disabled={ loginDisableState } onClick={ () => {
                doLogin(orderNo);
              } }>确认登录</Button>
            </Space.Compact>
          </>
        }/>

      </div>
    </PageContainer>
  }

  return (
    <PageContainer ghost loading={ pageLoading }>
      { contextHolder }
      <Modal
        title="请提交你的创意描述"
        open={ createModal }
        onOk={ handleOk }
        confirmLoading={ confirmLoading }
        onCancel={ handleCancel }
      >
        <p>
          <TextArea
            value={ prompt }
            onChange={ (e) => setPrompt(e.target.value) }
            placeholder="例如: 一个18岁的中国少年 穿着篮球运动服 白色的篮球裤 篮球场 投篮"
            autoSize={ {
              minRows: 3,
              maxRows: 5,
            } }
          />
        </p>
      </Modal>
      <Modal
        width={ 720 }
        title="创意任务列表"
        footer={ []}
        open={ createTaskModel }
        onOk={ () => setCreateTaskModel(false) }
        confirmLoading={ confirmLoading }
        onCancel={ () => setCreateTaskModel(false) }
      >
        <Table columns={ [
          { title: '任务id', dataIndex: 'id', key: 'id', width: 60 },
          { title: '提示词', dataIndex: 'prompt', key: 'prompt' },
          { title: '状态', dataIndex:'state_name', key:'state_name', width: 60 },
          { title: '尺寸', dataIndex: 'size', key: 'size' },
          { title: '积分消耗', dataIndex: 'credit', key: 'credit', width: 75 },
        ] } dataSource={ creativeTaskList } size="small" pagination={ false } />
        <div style={ { height: 10 } }></div>
        <Pagination align="center" current={ creativeTaskListParam.page } total={ creativeTaskListParam.total } pageSize={ 12 }
                    onChange={ (page) => setCreativeTaskListParam({...creativeTaskListParam, page: page }) }/>
      </Modal>
      <div className="user-center">
        <div className="header">
          <div className="user-info">
            <Avatar size={ 64 } src={ user?.avatar }/>
            <div className="details">
              <div className="nickname">用户名: { user?.user_name }</div>
              <div className="nickname">总积分: { user?.total_credit }</div>
            </div>
          </div>
          <div className="balance">
            <span>积分余额：</span>
            <strong>{ user?.balance }</strong>
          </div>
        </div>

        <div>
          <Button type="primary" onClick={ () => setCreateModal(true) }>新增创意</Button> &nbsp;
          <Button type="primary" onClick={ () => setCreateTaskModel(true) }>任务列表</Button> &nbsp;
          <Button type="primary" onClick={ () => {
            localStorage.removeItem('login-token');
            setUser(null);
          } }>退出登录</Button>
        </div>

        <hr style={ { margin: '20px 0' } }/>

        <div className="content">
          <Pagination align="center" current={ creativePage } total={ creativeTotal } pageSize={ 12 }
                      onChange={ (page) => setCreativePage(page) }/>
          <div style={ { height: 20 } }></div>
          <List
            grid={ { gutter: 16, column: 4 } }
            dataSource={ creatives }
            renderItem={ (item) => (
              <List.Item>
                <Card
                  cover={ <img alt={ item?.task?.prompt } src={ item?.thumb_path }/> }
                  onClick={ () => handleViewCreative(item) }
                >
                  <Card.Meta title={ item?.task?.prompt }/>
                </Card>
              </List.Item>
            ) }
          />
        </div>

        <Modal
          width={ 720 }
          closable={ false }
          style={ { top: 10 } }
          title={ "" }
          visible={ isModalVisible }
          footer={ [] }
          onCancel={ handleModalClose }
        >
          <div className="modal-content">
            <img className="modal-image" style={ { maxWidth: '100%' }} src={ isModalVisible ? selectedCreative?.image_path : "" } alt={ selectedCreative?.image_path }/>
            <div style={ { height: 10 } }></div>
            <div className="modal-info">
              <h3>提示词</h3>
              <p>{ selectedCreative?.task?.prompt }</p>
              <Flex justify="space-between">
                <div>
                  <h3>创意尺寸</h3>
                  <p>{ selectedCreative?.task?.size }</p>
                </div>
                <div>
                  <p>
                    <h3>下载</h3>
                    <Button type="primary" onClick={ () => {
                      window.open(selectedCreative?.image_path)
                    } }>下载原图</Button>
                  </p>
                </div>
                <div>
                  <p>
                    <h3>公开设置</h3>
                    <Button type={ selectedCreative?.is_public ? "default" : "primary" } onClick={ () => {
                      (async () => {
                        try {
                          await api(`creative/set-public?token=${ user?.login_token }`, {
                            "id": selectedCreative?.id,
                            "is_public": !selectedCreative?.is_public,
                          });
                          // @ts-ignore
                          setSelectedCreative({ ...selectedCreative, is_public: !selectedCreative?.is_public });
                          setCreatives([ ...creatives.map(item => {
                            if (item.id === selectedCreative?.id) {
                              return { ...item, is_public: !item.is_public };
                            }
                            return item;
                          }) ]);
                        } catch (e: Error | any) {
                          messageApi.open({
                            type: 'error',
                            content: <div>设置失败: { e?.message }</div>,
                          });
                          console.error(e);
                        }
                      })()
                    } }>
                      { selectedCreative?.is_public ? "已公开" : "公开" }
                    </Button>
                  </p>
                </div>
              </Flex>
            </div>
          </div>
        </Modal>
      </div>
    </PageContainer>
);
};

export default UserCenter;
